package freespiritsocial.io.user.ui.fragment.home

import android.Manifest
import android.os.Bundle
import com.permissionx.guolindev.PermissionX
import freespiritsocial.io.user.R
import freespiritsocial.io.user.base.BaseFragment
import freespiritsocial.io.user.databinding.FrgHomeBinding
import freespiritsocial.io.user.ext.init
import freespiritsocial.io.user.viewmodel.HomeViewModel
import freespiritsocial.io.user.weight.tablayout.listener.OnTabSelectListener

/**
 * @description 主页
 */
class HomeFrg: BaseFragment<HomeViewModel,FrgHomeBinding>(),OnTabSelectListener {

    private val exploreFrg = ExploreFrg()
    private val followingFrg = FollowingFrg()
    override fun layoutId(): Int = R.layout.frg_home

    override fun initView(savedInstanceState: Bundle?) = with(mDatabind) {
        viewModel = mViewModel
        click = Click()
        tab.setTabData(arrayOf(getString(R.string._explore),getString(R.string.following)))
        tab.setOnTabSelectListener(this@HomeFrg)
        initFragment()
        toConfirmPermission()
    }

    private fun toConfirmPermission() {
        val permissionList = ArrayList<String>()
        permissionList.add(Manifest.permission.ACCESS_FINE_LOCATION)
        permissionList.add(Manifest.permission.ACCESS_COARSE_LOCATION)
        PermissionX.init(this).permissions(
            permissionList
        ).request { _,grantedList,_ ->
            val contains = grantedList.contains(Manifest.permission.ACCESS_FINE_LOCATION)
            appViewModel.locationPermission.postValue(contains)
        }
    }

    private fun initFragment() {
        mDatabind.viewpager2.init(this,arrayListOf(exploreFrg,followingFrg),false)
        mDatabind.viewpager2.offscreenPageLimit = 1
    }

    override fun createObserver() {
        super.createObserver()
        mViewModel.page.observe(this,::switchFragment)
    }

    private fun switchFragment(page: Int) {
        mDatabind.viewpager2.currentItem = page
        mDatabind.tab.currentTab = page
    }

    fun switchPage(page: Int,refresh: Boolean = false) {
        mViewModel.page.postValue(page)
        if (refresh) followingFrg.refresh()
    }

    inner class Click {
    }

    override fun onTabSelect(position: Int) {
        switchPage(position)
    }

    override fun onTabReselect(position: Int) {
    }

    fun onReShow() {
        exploreFrg.resetMap()
    }
}